<template>
  <div class="page-container">
    <div class="page-header">
      <h1 class="page-title">销售记录</h1>
      <n-button type="primary" @click="$router.push('/sales/create')">
        <template #icon>
          <n-icon><AddOutline /></n-icon>
        </template>
        销售登记
      </n-button>
    </div>
    
    <!-- 搜索栏 -->
    <n-card style="margin-bottom: 16px;">
      <n-space>
        <n-input 
          v-model:value="searchParams.orderNo" 
          placeholder="搜索订单号" 
          clearable 
          style="width: 200px;"
        />
        <n-date-picker 
          v-model:value="searchParams.dateRange" 
          type="datetimerange" 
          clearable 
          placeholder="选择时间范围"
          style="width: 360px;"
        />
        <n-select 
          v-model:value="searchParams.status" 
          placeholder="状态" 
          clearable 
          :options="statusOptions"
          style="width: 150px;"
        />
        <n-button type="primary" @click="handleSearch">搜索</n-button>
        <n-button @click="handleReset">重置</n-button>
      </n-space>
    </n-card>
    
    <!-- 表格 -->
    <div class="table-wrapper">
      <n-data-table
        :columns="columns"
        :data="tableData"
        :loading="loading"
        :pagination="pagination"
        :bordered="false"
        @update:page="handlePageChange"
      />
    </div>
    
    <!-- 订单详情对话框 -->
    <n-modal v-model:show="showDetailModal" preset="dialog" title="订单详情" style="width: 800px;">
      <div v-if="currentOrder">
        <n-descriptions :column="2" bordered>
          <n-descriptions-item label="订单号">{{ currentOrder.orderNo }}</n-descriptions-item>
          <n-descriptions-item label="订单金额">¥{{ currentOrder.totalAmount }}</n-descriptions-item>
          <n-descriptions-item label="支付方式">{{ currentOrder.paymentMethod }}</n-descriptions-item>
          <n-descriptions-item label="操作员工">{{ currentOrder.employeeName }}</n-descriptions-item>
          <n-descriptions-item label="销售时间">{{ currentOrder.saleTime }}</n-descriptions-item>
          <n-descriptions-item label="状态">
            <n-tag :type="currentOrder.status === 1 ? 'success' : 'default'">
              {{ currentOrder.status === 1 ? '正常' : '已取消' }}
            </n-tag>
          </n-descriptions-item>
          <n-descriptions-item v-if="currentOrder.remark" label="备注" :span="2">
            {{ currentOrder.remark }}
          </n-descriptions-item>
        </n-descriptions>
        
        <n-divider />
        
        <h4 style="margin-bottom: 16px;">订单明细</h4>
        <n-table :single-line="false">
          <thead>
            <tr>
              <th>商品名称</th>
              <th>单价</th>
              <th>数量</th>
              <th>小计</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="item in currentOrder.items" :key="item.id">
              <td>{{ item.breadName }}</td>
              <td>¥{{ item.price }}</td>
              <td>{{ item.quantity }}</td>
              <td>¥{{ item.subtotal }}</td>
            </tr>
          </tbody>
        </n-table>
      </div>
    </n-modal>
  </div>
</template>

<script setup>
import { ref, h, onMounted, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { getOrderPage, getOrderDetail, cancelOrder } from '@/api/sales'
import { 
  NButton, NIcon, NCard, NSpace, NInput, NDatePicker, NSelect, NDataTable, NTag,
  NModal, NDescriptions, NDescriptionsItem, NDivider, NTable, useMessage, useDialog
} from 'naive-ui'
import { AddOutline, EyeOutline, CloseCircleOutline } from '@vicons/ionicons5'

const router = useRouter()
const userStore = useUserStore()
const message = useMessage()
const dialog = useDialog()

const loading = ref(false)
const tableData = ref([])
const showDetailModal = ref(false)
const currentOrder = ref(null)

const searchParams = reactive({
  orderNo: '',
  dateRange: null,
  status: null
})

const pagination = reactive({
  page: 1,
  pageSize: 10,
  itemCount: 0,
  showSizePicker: true,
  pageSizes: [10, 20, 50]
})

const statusOptions = [
  { label: '正常', value: 1 },
  { label: '已取消', value: 0 }
]

const columns = [
  { title: '订单号', key: 'orderNo', width: 180 },
  { 
    title: '订单金额', 
    key: 'totalAmount',
    render: (row) => `¥${row.totalAmount}`
  },
  { title: '支付方式', key: 'paymentMethod' },
  { title: '操作员工', key: 'employeeName' },
  { title: '销售时间', key: 'saleTime', width: 180 },
  { 
    title: '状态', 
    key: 'status',
    render: (row) => {
      return h(NTag, { type: row.status === 1 ? 'success' : 'default' }, { 
        default: () => row.status === 1 ? '正常' : '已取消' 
      })
    }
  },
  {
    title: '操作',
    key: 'actions',
    width: 200,
    render: (row) => {
      const actions = [
        h(NButton, {
          size: 'small',
          onClick: () => handleViewDetail(row)
        }, { 
          default: () => '查看',
          icon: () => h(NIcon, {}, { default: () => h(EyeOutline) })
        })
      ]
      
      // 只有店长且订单状态为正常时才显示取消按钮
      if (userStore.userInfo?.role === 'MANAGER' && row.status === 1) {
        actions.push(
          h(NButton, {
            size: 'small',
            type: 'error',
            onClick: () => handleCancel(row)
          }, { 
            default: () => '取消',
            icon: () => h(NIcon, {}, { default: () => h(CloseCircleOutline) })
          })
        )
      }
      
      return h(NSpace, {}, { default: () => actions })
    }
  }
]

async function loadData() {
  try {
    loading.value = true
    const params = {
      page: pagination.page,
      size: pagination.pageSize,
      orderNo: searchParams.orderNo || undefined,
      status: searchParams.status
    }
    
    if (searchParams.dateRange && searchParams.dateRange.length === 2) {
      params.startTime = new Date(searchParams.dateRange[0]).toISOString().slice(0, 19).replace('T', ' ')
      params.endTime = new Date(searchParams.dateRange[1]).toISOString().slice(0, 19).replace('T', ' ')
    }
    
    const res = await getOrderPage(params)
    tableData.value = res.data.records
    pagination.itemCount = res.data.total
  } catch (error) {
    message.error(error.message || '加载数据失败')
  } finally {
    loading.value = false
  }
}

function handleSearch() {
  pagination.page = 1
  loadData()
}

function handleReset() {
  searchParams.orderNo = ''
  searchParams.dateRange = null
  searchParams.status = null
  pagination.page = 1
  loadData()
}

function handlePageChange(page) {
  pagination.page = page
  loadData()
}

async function handleViewDetail(row) {
  try {
    const res = await getOrderDetail(row.id)
    currentOrder.value = res.data
    showDetailModal.value = true
  } catch (error) {
    message.error(error.message || '加载订单详情失败')
  }
}

function handleCancel(row) {
  dialog.warning({
    title: '确认取消订单',
    content: `确定要取消订单「${row.orderNo}」吗？取消后将恢复库存。`,
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: async () => {
      try {
        await cancelOrder(row.id, { reason: '店长取消订单' })
        message.success('订单已取消')
        loadData()
      } catch (error) {
        message.error(error.message || '取消订单失败')
      }
    }
  })
}

onMounted(() => {
  loadData()
})
</script>

